//
//  GYDCameraViewController.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/19.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit
import Photos

import SnapKit


class GYDCameraViewController: UIViewController{

    
    var photoSelectedBlock: ((image:UIImage) -> ())?
    
    
    private lazy var titleButton : GYDTitleButton = {
        () -> GYDTitleButton in
        let btn = GYDTitleButton(frame:CGRect(x: 0, y: 0, width: 150, height: 44))
        btn.addTarget(self, action: #selector(GYDCameraViewController.titleButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
    
    private lazy var imageManager : TZImageManager = {
        return TZImageManager()
    }()
    
    private var albumModel : TZAlbumModel?
    
    private var photoDic : [Int : UIImage]?
    
    
    private var albumModels : [TZAlbumModel]?
    
    private lazy var collectionView : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = UICollectionViewScrollDirection.Vertical
        layout.itemSize = CGSize(width: (GYDWindowWidth - 4)/3.0, height: (GYDWindowWidth - 4)/3.0)
        layout.minimumLineSpacing = 2
        layout.minimumInteritemSpacing = 2
        let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cellId")
        self.view.addSubview(collectionView)
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        setUpNavigationBar()
        
        getPhoto()
    }
    func getPhoto() -> Void {
        imageManager.getCameraRollAlbum(false, allowPickingImage: true) { [unowned self] (albumModel) in
            self.titleButton.setTitle(albumModel.name, forState: UIControlState.Normal)
            self.navigationItem.titleView = self.titleButton
            self.albumModel = albumModel
            self.collectionView.reloadData()
        }
    }
    
    @objc private func titleButtonClick() -> Void {
        if self.albumModels == nil {
            var tempAlbumModels : [TZAlbumModel]?
            imageManager.getAllAlbums(false, allowPickingImage: true, completion: { (albumModels) in
                tempAlbumModels = albumModels
            })
            if tempAlbumModels == nil {
                return;
            }
            self.albumModels = tempAlbumModels
        }
        titleButton.selected = !titleButton.selected
        GYDCameraAllAblumView.showWithAlbumArr(self.albumModels!) { (albumModel) in
            self.titleButton.selected = !self.titleButton.selected
            if albumModel != nil {
                if albumModel?.name != self.albumModel?.name {
                    self.titleButton.setTitle(albumModel?.name, forState: UIControlState.Normal)
                    self.albumModel = albumModel
                    self.photoDic?.removeAll()
                    self.collectionView.reloadData()
                }
            }
        }
    }
    
    func setUpNavigationBar() -> Void {
        
        let backBar = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(GYDCameraViewController.gotoBack))
        navigationItem.leftBarButtonItem = backBar
    }
    
    @objc private func gotoBack() -> Void {
        navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
}

extension GYDCameraViewController:UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if albumModel == nil {
            return 0
        }
        return (albumModel?.result?.count)!
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellId", forIndexPath: indexPath)
        let asset = albumModel?.result?.objectAtIndex(indexPath.item)
        var image : UIImage?
        if photoDic != nil {
            image = photoDic![indexPath.item]
        }else {
            photoDic = [0:UIImage()]
        }
        
        let view = cell.contentView.viewWithTag(800)
        var imageView : UIImageView?
        if view == nil {
            imageView = UIImageView()
            imageView!.contentMode = UIViewContentMode.ScaleAspectFill
            imageView!.clipsToBounds = true
            cell.contentView.addSubview(imageView!)
            imageView!.snp_makeConstraints(closure: { (make) in
                make.left.equalTo(0)
                make.bottom.equalTo(0)
                make.right.equalTo(0)
                make.top.equalTo(0)
            })
            imageView!.tag = 800
        }else {
            imageView = view as? UIImageView
        }
        if image == nil {
            self.imageManager.getPhotoWithAsset(asset, photoWidth: (GYDWindowWidth - 4)/3.0, completion: { [unowned self] (newImage, info, isDegraded) in
                imageView?.image = newImage
                self.photoDic![indexPath.item] = newImage
            })
        }else {
            imageView?.image = image
        }
        cell.backgroundColor = UIColor.whiteColor()
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let image = photoDic![indexPath.item];
        if image != nil {
            if let tempBlock = photoSelectedBlock {
                self.navigationController?.dismissViewControllerAnimated(false, completion: nil)
                tempBlock(image: image!)
            }
        }
    }
    
}

